package cn.ljy.common.utils.table;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 表格工具类
 * @author ljy
 * 20220721
 */
public class MyTableUtil {

    /**
     * 输出excel文件，提供下载。
     * 结合hutool工具使用
     * @param response
     * @param fileName  下载时显示的文件名称
     * @param writer
     */
    public static void downloadExcelByHutool(HttpServletResponse response, String fileName, ExcelWriter writer) {
        //response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        //response.setContentType("application/x-download");
        // 设置返回内容格
        //response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        // test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        ServletOutputStream out = null;
        try {
            fileName= URLEncoder.encode(fileName, "UTF-8") + ".xlsx";
            //fileName=new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)+".xlsx";
            // 设置请求头属性
            response.setHeader("Content-Disposition","attachment;filename="+fileName);
            //response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso-8859-1") + ".xlsx");
            //response.setHeader("Content-Disposition","attachment;filename=test.xlsx");
            //response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), StandardCharsets.ISO_8859_1));
            out = response.getOutputStream();
            // 写出到文件
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(writer!=null){
                // 关闭writer，释放内存
                writer.close();
            }
            if(out!=null){
                // 此处记得关闭输出Servlet流
                IoUtil.close(out);
            }
        }
    }

    /**
     * 通过流的方式输出excle到页面，每个文件都要下载
     * 结合原生poi使用
     * @param response 响应
     * @param workbook 表对象
     * @param fileName 文件名，下载时显示的文件名
     */
    public static void outExcelStream(HttpServletResponse response, Workbook workbook, String fileName){
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            response.setContentType("application/x-download");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1") + ".xlsx");
            workbook.write(os);
            os.flush();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 验证表格的列是否有重复的字段，包含空格
     * 说明：本方法注重性能，只判断是否重复，不给出重复的单元格信息
     * @param columns
     * @return
     */
    public static boolean validateRepeatColumn(List<Object> columns){
        boolean result=false;
        // 将表格内容统一转换为字符串再比较判断
        //List<String> columnsString = columns.stream().map(s -> String.valueOf(s)).collect(Collectors.toList());
        Set<String> columnsStringSet = columns.stream().map(s -> String.valueOf(s)).collect(Collectors.toSet());
        //如果转为set集合后长度不一致，则表示有重复的字段
        if(columnsStringSet.size()!=columns.size()){
            result=true;
        }
        return result;
    }
}
